<?php

// +----------------------------------------------------------------------
// | 附件模型
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\file;

use app\common\event\Base;
use think\File;

class Common extends Base
{

    /**
     * @param File $file 要上传的文件
     * @param array $setting
     * @param string $uploadDir
     * @return array
     */
    protected function _formatInfo(File $file, array $setting, string &$uploadDir): array
	{
        $insert = [];
        $insert['type'] = 'normal';
        $insert['md5'] = $file->md5();
        $insert['sha1'] = $file->sha1();
        // 默认本地驱动
        $insert['driver'] = $setting['driver'];
        $insert['mime'] = $file->getMime();
        $insert['name'] = $file->getOriginalName();
        if ($insert['name'] == 'blob') {
            // 截图文件
            $insert['name'] = '截图' . time_format(time(), 'ymdHis') . rand(100, 999) . '.' . (explode('/', $insert['mime'])[1]);
            $insert['remark'] = $insert['name'];
            $insert['size'] = $file->getSize();
            $insert['ext'] = pathinfo($insert['name'], PATHINFO_EXTENSION);
        } else {
            $insert['remark'] = $insert['name'];
            $insert['size'] = $file->getSize();
            $insert['ext'] = pathinfo($insert['name'], PATHINFO_EXTENSION);
        }

		//上传文件命名规则，默认为date，date-根据日期和微秒数生成，md5-对文件使用md5_file散列生成，sha1-对文件使用sha1_file散列生成
        $insert['save_path'] = 'uploads' . DIRECTORY_SEPARATOR . $setting['save_path'] . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, time_format(time(), 'Ym/d') . DIRECTORY_SEPARATOR);
        if (!$insert['ext']) {
            $insert['save_name'] = uniqid();
        } else {
            $insert['save_name'] = uniqid() . '.' . $insert['ext'];
        }
        $insert['path'] = $insert['save_path'] . $insert['save_name'];
        $uploadDir = pathinfo(public_path() . $insert['path'])['dirname'];
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        $uploadDir .= DIRECTORY_SEPARATOR;
        return $insert;
    }
}
